package co.yixiang.modules.user.service.impl;

import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.distributor.domain.YxDistributor;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserDistributorRelation;
import co.yixiang.modules.user.service.YxUserDistributorRelationService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.dto.YxUserDistributorRelationQueryCriteria;
import co.yixiang.modules.user.service.dto.YxUserDto;
import co.yixiang.modules.user.service.mapper.UserDistributorRelationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author hupeng
 * @date 2020-05-12
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxUserDistributorRelationServiceImpl extends BaseServiceImpl<UserDistributorRelationMapper, YxUserDistributorRelation> implements YxUserDistributorRelationService {

    @Autowired
    private IGenerator generator;

    @Autowired
    private YxUserService userService;


    @Override
    public List<YxUserDistributorRelation> getByDistributorId(String distributorId) {
        LambdaQueryWrapper<YxUserDistributorRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxUserDistributorRelation::getDistributorId, distributorId);
        return this.list(wrapper);
    }

    @Override
    public YxUserDistributorRelation getByUid(Long uid) {
        LambdaQueryWrapper<YxUserDistributorRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxUserDistributorRelation::getUid, uid);
        return this.getOne(wrapper);
    }

    @Override
    public YxUserDistributorRelation getByUsername(String username) {
        LambdaQueryWrapper<YxUserDistributorRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxUserDistributorRelation::getUsername, username);
        return this.getOne(wrapper);
    }

    @Override
    public Map<String, Object> queryAll(YxUserDistributorRelationQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxUserDistributorRelation> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxUserDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public List<YxUserDistributorRelation> queryAll(YxUserDistributorRelationQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxUserDistributorRelation.class, criteria));
    }

    @Override
    public void refreshDistributor(YxDistributor distributor) {
        String[] tels = distributor.getLinkTel().split(",");

        //查询该经销商是否已经有关联关系,通过手机号关联
        List<YxUserDistributorRelation> userDistributorRelationList = this.getByDistributorId(distributor.getDistributorId());
        Map<String, YxUserDistributorRelation> relationMap = userDistributorRelationList.stream().collect(Collectors.toMap(YxUserDistributorRelation::getUsername, Function.identity()));

        List<Long> removeRelationList = new ArrayList<>();

        for (String phone : tels) {
            //包含phone不需要处理，移除掉
            if (relationMap.containsKey(phone)) {
                relationMap.remove(phone);
                continue;
            }
        }

        //relationMap还有值是需要删除的
        for (Map.Entry<String, YxUserDistributorRelation> entry : relationMap.entrySet()) {
            removeRelationList.add(entry.getValue().getId());
        }

        if (!removeRelationList.isEmpty()) {
            this.removeByIds(removeRelationList);
        }
    }

    @Override
    public void relationUserAndDistributor(YxUser user, YxDistributor distributor) {
        //查询关联关系
        YxUser newUser = userService.findByUserName(user.getUsername());
        YxUserDistributorRelation userDistributorRelation = this.getByUid(newUser.getUid());

        if (Objects.isNull(userDistributorRelation)) {
            //建立关联关系
            userDistributorRelation = YxUserDistributorRelation.builder()
                    .uid(newUser.getUid())
                    .username(newUser.getUsername())
                    .phone(newUser.getPhone())
                    .distributorId(distributor.getDistributorId())
                    .distributorName(distributor.getDistributorName())
                    .build();
            this.save(userDistributorRelation);
        }
    }
}
